<?php
/**
 * @author lan7
 * @since 2010-09-27
 */
if(!defined('IN_ORA')) {
	exit('Access Denied');
}
$GLOBALS['__msg_tpl__'] = "admin/msg.html";
session_start();
if(!isset($_SESSION["admin"])){
	exit('Access Denied');
}
$act = $GLOBALS['act'];
$GLOBALS['tpl']->assign('act',$act);

////////////////
/** 文章列表 **/
if($act == 'list'){
	$pid = is_numeric($GLOBALS['_param']['p'])?$GLOBALS['_param']['p']:1;
	$psize = $GLOBALS['_param']['psize']?$GLOBALS['_param']['psize']:$GLOBALS['ora_cfg']['page_size'];
	$total = $GLOBALS['db']->count("select count(*) from ".tn('article'));
	import("lib.page");
	$pobj = new page('p',$pid,$total,$psize);
	$sql = "select oa.*,oc.cat_name from  ".tn("article")." oa inner join ( select Id from  ".tn("article");
	$sql .= " order by Id desc limit ".$pobj->sqlParam.") b using(Id) left join ".tn("cat")." oc on oa.cat_id = oc.Id";
	if($pid >= intval($pobj->maxPage/2)){
		$sql = "select oa.*,oc.cat_name from  ".tn("article")." oa inner join ( select Id from  ".tn("article");
		$sql .= " order by Id asc limit ".$pobj->sqlParam.") b using(Id) left join ".tn("cat")." oc on oa.cat_id = oc.Id";
	}
	$GLOBALS['tpl']->assign("pobj",$pobj);
	$GLOBALS['tpl']->assign('url',preg_replace('/\-?p(\-|_)\d+/i',"",get_urlStr()));
	$GLOBALS['tpl']->assign('arts',$GLOBALS['db']->getAll($sql));
}
/** 添加/修改 **/
else if($act == 'add'|$act == 'modify'){
	/* 获取文章类别 */
	import("lib.cat");
	$GLOBALS['tpl']->assign('cats',cat_lib::getSubChild(0,3,' and cat_type = 0 '));
	$id = $GLOBALS['_param']['id'];
	if(is_numeric($id)&&$id!=""){
		$sql = "select oa.*,oc.content from ".tn("article")." oa left join ".tn("content")." oc on oa.id = oc.fk_id where oc.ctype = 0  and oa.Id = $id";
		$GLOBALS['tpl']->assign("art",$GLOBALS['db']->getOne($sql));
	}
}
/** Add Or Update  **/
else if($act == 'save'){
	$art_id = $_POST["id"];
	$title = htmlspecialchars($_POST["title"]);
	if(empty($title)||$title==""){
		showMsg("动态标题不能为空!",$_SERVER["HTTP_REFERER"],1);
	}
	$source = htmlspecialchars($_POST["source"]);
	$author = htmlspecialchars($_POST["author"]);
	$keywords = htmlspecialchars($_POST["keywords"]);
	$cat_id = $_POST["cat_id"];
	if(empty($cat_id)||!is_numeric($cat_id)){
		showMsg("请选择类别!",$_SERVER["HTTP_REFERER"],1);
	}
	$getWay = ($_POST["getWay"])?true:false;
	$content = $_POST["content"];
	if(empty($content)||$content == ""){
		showMsg("动态内容不能为空!",$_SERVER["HTTP_REFERER"],1);
	}
	$pic = $_POST["pic"];
	if(isset($_POST["getWay"])){
		if($_POST["getWay"]=='true'){
			//重新提取
			$pic = getImg($content);
		}else{
			//本地上传
			import("lib.upload");
			$up = new Upload("jpg|gif|png");
			if(!$up->errInfo){
				$pic = "upload/".$up->files[0]["urlPath"];
				import("lib.image");
				image::thumb(ROOT_PATH.$pic,'','',100,80);
			}else{
				showMsg("图片上传失败!",$_SERVER["HTTP_REFERER"],1);
			}
		}
	}
	$content = htmlspecialchars($content);
	$tags = $_POST["tags"];
	$tags = explode(",",$tags);
	$tags = array_map("clear_html",$tags);
	array_unique($tags);
	$tags = array_filter($tags, "loseSpace");
	$tagsstr = implode(",",$tags);
	$status = isset($_POST["status"])?1:0;
	if($art_id == "" || !is_numeric($art_id)){
		//addNew
		$sql =  "insert into ".tn("article")."(title,source,author,keywords,cat_id,pic,status,tags,dateline) ";
		$sql .= " values ('$title','$source','$author','$keywords',$cat_id,'$pic',$status,'$tagsstr',".time().")";
		$art_id = $GLOBALS['db']->addNew($sql);
		if(!is_numeric($art_id)){
			@io::remove(UPLOAD_PATH.$pic);//删除图片
			@io::remove(UPLOAD_PATH.timg($pic));//删除缩略图
			showMsg("新增失败!",$_SERVER["HTTP_REFERER"],1);
		}else{
			$sql = "insert into ".tn("content")."(content,ctype,fk_id) values('$content',0,$art_id)";
			$GLOBALS['db']->execute($sql);
			/* 先清空 tags 与 Art 之间的对应关系 */
			$sql = "delete from ".tn("tags")." where tag_type = 0 and fk_id = $art_id";
			$GLOBALS['db']->execute($sql);
			/* 重新入库 */
			foreach ($tags as $k=>$v){
				$sql = "insert into ".tn("tags")."(tag_name,tag_type,fk_id) values('$v',0,$art_id)";
				$GLOBALS['db']->execute($sql);
			}
			showMsg("操作成功!",parse_uri("admin_article-list"),1);
		}
	}else{
		//UpDate
		$sql = "update ".tn("article")." set title='$title',source='$source',author='$author',keywords='$keywords',cat_id=$cat_id,pic='$pic',status=$status,tags='$tagsstr' where Id = $art_id";
		$GLOBALS['db']->execute($sql);
		$sql = "update ".tn("content")." set content = '$content' where ctype=0 and fk_id = $art_id";
		$GLOBALS['db']->execute($sql);
		/* 先清空 tags 与 Art 之间的对应关系 */
		$sql = "delete from ".tn("tags")." where tag_type = 0 and fk_id = $art_id";
		$GLOBALS['db']->execute($sql);
		/* 重新入库 */
		foreach ($tags as $k=>$v){
			$sql = "insert into ".tn("tags")."(tag_name,tag_type,fk_id) values('$v',0,$art_id)";
			$GLOBALS['db']->execute($sql);
		}
		showMsg("更新成功!",parse_uri("admin_article-list"),1);
	}
}
/** 删除文章 **/
else if($act == 'del'){
	$id = $GLOBALS['_param']['id'];
	if($id!=""&&is_numeric($id)){
		$art = $GLOBALS['db']->getOne("select * from ".tn("article")." where Id = $id");
		if($art){
			//删除图片
			if($art['pic']){
				@io::remove(UPLOAD_PATH.$art['pic']);
				@io::remove(UPLOAD_PATH.timg($art['pic']));
			}
			//删除标签
			$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 0 and fk_id = {$art['Id']}");
			//删除内容
			$GLOBALS['db']->execute("delete from ".tn("content")." where ctype = 0 and fk_id = {$art['Id']}");
			//删除文章
			$GLOBALS['db']->execute("delete from ".tn("article")." where Id = {$art['Id']}");
			showMsg("删除成功!",parse_uri("admin_article-list"),1);
		}
	}else{
		$id = $_POST["id"];
		if(!empty($id)&&is_array($id)){
			foreach ($id as $k =>$v){
				delArt($v);
			}
		}
		showMsg("删除成功!",parse_uri("admin_article-list"),1);
	}
}
/** 审核文章 **/
else if($act == 'pass'){
	$id = $_POST["id"];
	if($id!=""&&is_array($id)){
		$id = array_filter($id,"filt");
		$GLOBALS['db']->execute("update ".tn("article")." set status = 1 where Id in (".implode(",",$id).")");
		showMsg("审核成功!",parse_uri("admin_article-list"),1);
	}
	showMsg("请选择待审核的文章!",parse_uri("admin_article-list"),1);
}
/** 推荐文章 **/
else if($act == 'recommend'){
	$id = $_POST["id"];
	if($id!=""&&is_array($id)){
		$id = array_filter($id,"filt");
		$GLOBALS['db']->execute("update ".tn("article")." set status = 2 where Id in (".implode(",",$id).")");
		showMsg("操作成功!",parse_uri("admin_article-list"),1);
	}
	showMsg("请选择待审核的文章!",parse_uri("admin_article-list"),1);
}
$GLOBALS['tpl']->display('admin/article.html');


//************///
/** 提取图片并保存到本地 **/
function getImg(&$content){
	$tmp = array();
	if($content!=""){
		$content = stripslashes_deep($content);
		preg_match_all('/<img.*?src=["|\'](.*?)["|\'].*?\/?>/i',$content,$tmp);
		$rs = "";
		for ($j=0;$j<sizeof($tmp[1]);$j++){
			if(!empty($tmp[1][$j]) && (strpos($tmp[1][$j],HTTP_HOST)===false)){
				$imgName = rand_string(12).".jpg";
				$hdl = fopen($tmp[1][$j], "rb");
				$contents = "";
				while (!feof($hdl)) {
					$contents .= fread($hdl, 8192);
				}
				io::write(UPLOAD_PATH."http/".$imgName,$contents);
				if($rs == ""){
					$rs = $imgName;//取第一张
				}
				$content = str_replace($tmp[1][$j],HTTP_HOST."/upload/http/".$imgName,$content);
			}
		}
		return "upload/http/".$rs;
	}
	return "";
}

/** 过滤空字符串 **/
function loseSpace($val){
	return (trim($val) == "")?false:true;
}
/** 删除文件及其相关数据 **/
function delArt($id){
	$art = $GLOBALS['db']->getOne("select * from ".tn("article")." where Id = $id");
	if($art){
		//删除图片
		if($art['pic']){
			@io::remove(UPLOAD_PATH.$art['pic']);
			@io::remove(UPLOAD_PATH.timg($art['pic']));
		}
		//删除标签
		$GLOBALS['db']->execute("delete from ".tn("tags")." where tag_type = 0 and fk_id = {$art['Id']}");
		//删除内容
		$GLOBALS['db']->execute("delete from ".tn("content")." where ctype = 0 and fk_id = {$art['Id']}");
		//删除文章
		$GLOBALS['db']->execute("delete from ".tn("article")." where Id = {$art['Id']}");
	}else{
		return false;
	}
}
/** 过滤非数字元素 **/
function filt($v){
	return is_numeric($v);
}
?>